import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './userStore'
import { insertCartAPI, getCartListAPI, deleteCartAPI } from '@/apis/cart'

export const useCartStore = defineStore(
  'cart',
  () => {
    // 购物车数据
    const cartData = ref([])
    // 获取用户信息token
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    // 添加商品到购物车
    const addCart = async (goods) => {
      const { skuId, count } = goods
      if (isLogin.value) {
        await insertCartAPI({ skuId, count })
        upDataNewList()
        return
      }
      const item = cartData.value.find((item) => item.id === goods.id)
      if (item) {
        item.count += 1
      } else {
        cartData.value.push(goods)
      }
    }
    // 删除购物车商品
    const removeCart = async (skuId) => {
      if (isLogin.value) {
        await deleteCartAPI([skuId])
        upDataNewList()
        return
      }
      cartData.value = cartData.value.filter(
        (product) => product.skuId !== skuId
      )
    }
    // 获取最新购物车数据
    const upDataNewList = async () => {
      if (isLogin.value) {
        const res = await getCartListAPI()
        cartData.value = res.result
        return
      }
    }
    // 清除购物车列表
    const clearCart = () => {
      cartData.value = []
      upDataNewList()
    }
    // 单选功能
    const singleChange = (skuId, selected) => {
      cartData.value.find((item) => {
        if (item.skuId === skuId) {
          item.selected = selected
        }
      })
    }
    // 全选
    const allCheck = (selected) => {
      cartData.value.forEach((item) => {
        item.selected = selected
      })
    }

    // 计算属性
    // 是否全选
    const isAll = computed(() => cartData.value.every((item) => item.selected))


    // 选中个数
    const selectedCount = computed(() =>
      cartData.value.reduce(
        (count, item) => (item.selected ? count + item.count : count),
        0
      )
    )
    // 选中商品的价钱
    const selectedPrice = computed(() => {
      return cartData.value
        .filter((item) => item.selected)
        .reduce((count, item) => count + item.price * item.count, 0)
    })
    
    return {
      cartData,
      addCart,
      removeCart,
      singleChange,
      isAll,
      allCheck,
      selectedCount,
      selectedPrice,
      clearCart,
      upDataNewList
    }
  },
  { persist: true }
)